<!--
 * @FileDescription 实训
 * @Author lz
 * @Date 20230131 13:55:37
 * @LastEditors lz
 * @LastEditTime 20230131 13:55:37
-->
<template>
    <div class="wp">
        <!-- 顶部 -->
        <hdrModel Hierarchy="2" :ID="newArr.get(state.StoragePath)"></hdrModel>
        <div class="times" v-if="HomeContent.Default.ApplicationType.value == '考核'">
            <span v-if="HomeContent.Default.Duration.value">00:{{ formattedMinutes }}:{{ formattedSeconds }}</span>  
            <span v-else>{{ TM(state.times) }}</span>
        </div>
        <div class="Btn" @click="submit()" v-if="HomeContent.Default.ApplicationType.value == '考核'">
            提交
        </div>
        <!-- 列表 -->
        <div class="Sidebar" v-if="state.showHide">
            <div class="putAway" @click="show()"></div>
            <div class="ListOptions">
                <div class="statistics">
                    <img src="/images/list_sign_select.png">
                    实训项目( {{ state.AnsweredNum }}/{{ simulationData.Default.trainingDatalist.value.length }})
                </div>
                <div class="optionList" v-for="(item, index) in simulationData.Default.trainingDatalist.value" :key="index"
                    @click="selectBtn(item, index)" :class="item.state == 2 ? 'ChickOut' : ''">
                    {{ item.Name + item.Type }}
                    <img src="/images/Checkmark.png" v-if="item.IsSubmit">
                </div>
            </div>
        </div>
        <div class="SidebarHide" v-if="!state.showHide">
            <div class="openBar" @click="show()"></div>
        </div>

        <judge @doSth="showTips" v-if="state.topicType == '结构'"
            :Answer="simulationData.Default.trainingDatalist.value[state.choiceIndex].Answer"
            :Questions="simulationData.Default.trainingDatalist.value[state.choiceIndex].Questions">
        </judge>

        <theBlanks @doSth="showTips" v-if="state.topicType == '参数'"></theBlanks>

        <principle @doSth="showTips" v-if="state.topicType == '原理'"
            :Answer="simulationData.Default.trainingDatalist.value[state.choiceIndex].Answer"
            :Questions="simulationData.Default.trainingDatalist.value[state.choiceIndex].Questions"
            :Dialogues="simulationData.Default.trainingDatalist.value[state.choiceIndex].Dialogues"></principle>

        <choice @doSth="showTips" v-if="state.topicType == '组成'"></choice>

        <promptBox ref="childRef"></promptBox>

        <subpro ref="subproRef"></subpro>

        <messageBox ref="messageBoxRef" :Questions="state.Questions" :messageType="state.messageType"
            :ID="newArr.get(state.StoragePath)"></messageBox>

        <Speak hidden ref="audioRef" :stats="HomeContent.Default.pausableType.value"
            v-show="HomeContent.Default.VoiceControl.value">
            {{ state.VoiceValue }}
        </Speak>

    </div>
</template>

<script setup lang="ts">

import Speak from '@components/TTS/Speak.vue';

import hdrModel from '../header/index.vue'
import judge from './model/judge.vue'
import choice from './model/choice.vue'
import theBlanks from './model/theBlanks.vue'
import promptBox from './model/promptBox.vue'
import principle from './model/principle.vue'
import subpro from './model/subpro.vue'
import simulationData from '../simulationTraining/simulationTraining';

import { reactive, ref, toRefs, onBeforeMount, onMounted, onBeforeUpdate, onUpdated, onUnmounted, StyleValue, defineProps, defineEmits, watch, computed } from 'vue'
import OrbitCameraComponent from '@components/Apps/InertialNavigation/OrbitCameraComponent'
import { ClientMessage } from '@runtime/generate/message/ClientMessage'
import WebSocketComponent from '@runtime/module/WebSocket/WebSocketComponent'
import AnimatorComponent from '@runtime/UnityEngineBridge/AnimatorComponent'
import AssetLoaderComponent from '@runtime/UnityEngineBridge/AssetLoaderComponent'
import GameObjectComponent from '@runtime/UnityEngineBridge/GameObjectComponent'
import LabelComponent from '@runtime/UnityEngineBridge/LabelComponent'
import MessageCode from '../MessageCode'
import HomeContent from '../HomeContent'
import messageBox from '../messageBox.vue'
import HighlighterComponent from '@runtime/UnityEngineBridge/HighlighterComponent'
import { useRouter } from 'vue-router'
const router = useRouter()
const audioRef = ref()

const state = reactive({
    showHide: true,
    optionList: [{
        name: '1.xxx组成',
        types: 2,
        state: 1,
    }, {
        name: '2.xxx组成',
        types: 1,
        state: 1,
    }, {
        name: '3.xxx组成',
        types: 1,
        state: 1,
    }],
    topicType: '',
    StoragePath: '',
    Answered: 0,
    choiceIndex: -1,
    AnsweredNum: 0,
    times: 0,  //用时毫秒数
    timer: 0,  // 定时器对象
    Questions: '',
    messageType: 0,
    VoiceValue: '',
});

// 已加载模型数组
let newArr = ref(new Map())
let Id: number = 0
let PerD: any = {}
async function selectBtn(val: any, index: number) {
    // 切换重新加载audio
    // audioRef.value.replay()
    console.log('val',index,val);
    if(!HomeContent.Default.ispPausePlay.value) {
        await WebSocketComponent.Default.PostMessageAsync(new ClientMessage.StartPlaySoundRequest(val.Questions))
    }
    
    //清除旋转
    WebSocketComponent.Default.PostMessage(new ClientMessage.OrbiiCameraAutoObservationMessage())

    if (index == state.choiceIndex) {
        return
    }

    // 清除高亮
    await HighlighterComponent.Default.ClearAsync();

    LabelComponent.Default.Clear()
    state.choiceIndex = index
    simulationData.Default.subscript.value = index
    if (state.StoragePath != '') {
        // 隐藏模型
        await GameObjectComponent.Default.HideAsync(newArr.value.get(state.StoragePath));
    }


    if (newArr.value.get(val.Asset) == undefined) {
        //首次加载
        Id = await AssetLoaderComponent.Default.LoadAsync(val.Asset);
        // 视角
        const PerspectiveData: ClientMessage.StructureAdapterResponse = await WebSocketComponent.Default.PostMessageAsync(new ClientMessage.StructureAdapterRequest(MessageCode.Default.MsgCodesList.STRUCTURE_GET_VIEW, val.Asset + val.Type))
        PerD = JSON.parse(PerspectiveData.Content).Result
        await OrbitCameraComponent.Default.UpdateV2Async(PerD.TargetContainer, PerD.Horizontal, PerD.Vertical, PerD.Distance, PerD.MinDistance, PerD.MaxDistance, PerD.RotateSensitivity, PerD.RotateSensitivity, PerD.ScrollSensitivity);
        // 储存键值对
        newArr.value.set(val.Asset, Id)
        state.StoragePath = val.Asset
        // 模型动画
        if (val.Type == '组成' || val.Type == '原理') {
            await AnimatorComponent.Default.PlayAsync(Id, 'Default', 2000)
        }
        if (val.Type == '组成' || val.Type == '参数') {
            // 标签方法
            console.log('#####################');
            
            await LabelComponent.Default.LoadAsync(newArr.value.get(val.Asset))
        }
    } else {
        // console.log('已加载')
        // 显示模型
        await GameObjectComponent.Default.ShowAsync(newArr.value.get(val.Asset));
        // 视角
        const PerspectiveData: ClientMessage.StructureAdapterResponse = await WebSocketComponent.Default.PostMessageAsync(new ClientMessage.StructureAdapterRequest(MessageCode.Default.MsgCodesList.STRUCTURE_GET_VIEW, val.Asset + val.Type))
        PerD = JSON.parse(PerspectiveData.Content).Result
        await OrbitCameraComponent.Default.UpdateV2Async(PerD.TargetContainer, PerD.Horizontal, PerD.Vertical, PerD.Distance, PerD.MinDistance, PerD.MaxDistance, PerD.RotateSensitivity, PerD.RotateSensitivity, PerD.ScrollSensitivity);
        // 储存键值对
        state.StoragePath = val.Asset
        // 模型动画
        if (val.Type == '组成' || val.Type == '原理') {
            await AnimatorComponent.Default.PlayAsync(newArr.value.get(val.Asset), 'Default', 2000)
        }
        if (val.Type == '组成' || val.Type == '参数') {
            // 标签方法
            await LabelComponent.Default.LoadAsync(newArr.value.get(val.Asset))
        }
    }
    state.topicType = val.Type
    simulationData.Default.trainingDatalist.value.forEach(i => {
        if ((i.Name + i.Type) == (val.Name + val.Type)) {
            i.state = 2
        } else {
            i.state = 1
        }
    });

    if (val.Type == '结构') {
        state.VoiceValue = simulationData.Default.trainingDatalist.value[state.choiceIndex].Questions
    } else if (val.Type == '组成') {
        state.VoiceValue = '请将下列名称拖入到对应的部件框里'
    } else if (val.Type == '参数') {
        state.VoiceValue = '请将该部件的参数信息补充完整'
    } else if (val.Type == '原理') {
        state.VoiceValue = '请根据技师A和技师B的描述，做出正确判断'
    }
    setTimeout(() => {
        HomeContent.Default.pausableType.value.pausable = false
    }, 1000);

}
function show() {
    state.showHide = !state.showHide
}
const childRef = ref<any>();
const subproRef = ref<any>();
const messageBoxRef = ref<any>();

async function showTips(val: boolean) {
    if (HomeContent.Default.ApplicationType.value == '训练') {
        // 训练模式
        childRef.value.show(val)
        state.AnsweredNum = 0
        if (val == true) {
            simulationData.Default.trainingDatalist.value[state.choiceIndex].IsRight = true
            simulationData.Default.trainingDatalist.value[state.choiceIndex].IsSubmit = true
        } else if (val == false) {
            simulationData.Default.trainingDatalist.value[state.choiceIndex].IsRight = false
            simulationData.Default.trainingDatalist.value[state.choiceIndex].IsSubmit = false
        }
        simulationData.Default.trainingDatalist.value.forEach(item => {
            if (item.IsSubmit) {
                state.AnsweredNum++
            }
            if (state.AnsweredNum == simulationData.Default.trainingDatalist.value.length) {
                if (HomeContent.Default.CacheFullData.value) {
                  setTimeout(() => {
                    state.Questions = '训练完成是否退出程序！'
                    state.messageType = 3
                    messageBoxRef.value.showModel()
                  }, 1000);
                } else {
                    setTimeout(() => {
                    state.Questions = '训练完成是否返回考核设置页！'
                    state.messageType = 1
                    messageBoxRef.value.showModel()
                  }, 1000);
                }
                
            }
        });
    } else if (HomeContent.Default.ApplicationType.value == '考核') {
        subproRef.value.show()
        // 考核模式
        state.AnsweredNum = 0
        if (val == true) {
            simulationData.Default.trainingDatalist.value[state.choiceIndex].IsRight = true
        } else if (val == false) {
            simulationData.Default.trainingDatalist.value[state.choiceIndex].IsRight = false
        }
        simulationData.Default.trainingDatalist.value[state.choiceIndex].IsSubmit = true
        simulationData.Default.trainingDatalist.value.forEach(item => {
            if (item.IsSubmit) {
                state.AnsweredNum++
            }
        });
        let newData = {
            IsRight: simulationData.Default.trainingDatalist.value[state.choiceIndex].IsRight,
            IsSubmit: simulationData.Default.trainingDatalist.value[state.choiceIndex].IsSubmit,
            Id: simulationData.Default.trainingDatalist.value[state.choiceIndex]._id,
        }
        await WebSocketComponent.Default.PostMessageAsync(new ClientMessage.StructureAdapterRequest(MessageCode.Default.MsgCodesList.STRUCTURE_SUBMIT_CURRENT_TASK, JSON.stringify(newData)))
    }
    console.log('????????????????',simulationData.Default.trainingDatalist.value);
}

// ============================================================================================
// 倒计时
// console.log("HomeContent.Default.Duration.value", HomeContent.Default.Duration.value);

const remainingTime = ref(HomeContent.Default.Duration.value * 1000);
// const remainingTime = ref(0.1 * 60 * 1000);

// let timer: any = null;
function startCountdown() {
  HomeContent.Default.timerControl.value = setInterval(() => {
    remainingTime.value -= 1000;
    if (remainingTime.value <= 0) {
      // 模拟一次点击提交
      submit();
      clearInterval(HomeContent.Default.timerControl.value);
      HomeContent.Default.timerControl.value = null;
    }
  }, 1000);
}
const formattedMinutes = computed(() => {
  const minutes = Math.floor(remainingTime.value / 60000);
  return minutes.toString().padStart(2, "0");
});

const formattedSeconds = computed(() => {
  const seconds = Math.floor((remainingTime.value % 60000) / 1000);
  return seconds.toString().padStart(2, "0");
});
// ===================================================================================================

//提交
async function submit() {
    let tim = state.times / 1000
    // state.messageType = 2
    // state.Questions = '是否提交考核！'
    // messageBoxRef.value.showModel(tim)

    // 提交任务
    await WebSocketComponent.Default.PostMessageAsync(new ClientMessage.StructureAdapterRequest(MessageCode.Default.MsgCodesList.STRUCTURE_SUBMIT, `${tim}`))
    //跳转评价            
    router.push('summaryPage')   
}
//时间转
function TM(ms: number) {
    let h: string | number = Math.floor(ms / 1000 / 60 / 60)
    let m: string | number = Math.floor(ms / 1000 / 60)
    let s: string | number = Math.floor(ms / 1000)

    if (h === 1) {
        // 当时间刚好是60分钟时，让它以mm:ss格式显示,即显示60:00,而不是显示01:00:00
        if (m / 60 === 1 && s % 60 === 0) {
            h = ''
            m = '60:'
        } else {
            h = '01:'
            m = addZero(m % 60) + ':'
        }
        s = addZero(s % 60)
    } else {
        h = h === 0 ? '' : addZero(h) + ':'
        m = addZero(m % 60) + ':'
        s = addZero(s % 60)
    }
    return h + m + s
}
// 进行补0操作
function addZero(n: string | number) {
    //@ts-ignore
    return n < 10 ? '0' + n : n
}
onMounted(() => {
    HomeContent.Default.pausableType.value.pausable = true

    simulationData.Default.trainingDatalist.value.forEach(i => {
        i.state = 1
    });
    // 60s倒计时
    state.timer = window.setInterval(() => {
        state.times += 1000
        if (state.times == 3600000) {
            clearInterval(state.timer);
            state.timer = 0;
        }
    }, 1000);
    //首次加载调用点击方法
    selectBtn(simulationData.Default.trainingDatalist.value[0], 0)
    console.log('simulationData.Default.trainingDatalist.value',simulationData.Default.trainingDatalist.value);
    startCountdown()
});

</script>

<style scoped>
.wp {
    width: 100%;
    height: 100%;
    box-sizing: border-box;
    position: relative;
}


.Sidebar {
    position: absolute;
    top: 161px;
    left: -6px;
    width: 300px;
    height: 771px;
    background-image: url('/images/MenuBorder_bg.png');
    background-repeat: no-repeat;
    background-size: 100% 100%;
}

.SidebarHide {
    position: absolute;
    top: 0;
    left: 0;
    width: 60px;
    height: 1044px;
}

.putAway {
    position: absolute;
    top: 350px;
    right: -50px;
    width: 66px;
    height: 81px;
    background-image: url('/images/collapseArrow.png');
    background-repeat: no-repeat;
    background-size: 100% 100%;
}

.openBar {
    position: absolute;
    top: 500px;
    right: 0px;
    width: 66px;
    height: 81px;
    background-image: url('/images/collapseArrowHide.png');
    background-repeat: no-repeat;
    background-size: 100% 100%;
}

.ListOptions {
    width: 280px;
    height: 691px;
    margin-top: 46px;
    overflow-y: auto;
}

.ListOptions::-webkit-scrollbar {
    /*滚动条整体样式*/
    width: 6px;
    /*高宽分别对应横竖滚动条的尺寸*/
    height: 1px;
}

.ListOptions::-webkit-scrollbar-thumb {
    /*滚动条里面小方块*/

    border-radius: 10px;
    -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    background: #45B5FF;
}

.ListOptions::-webkit-scrollbar-track {
    /*滚动条里面轨道*/

    -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    border-radius: 10px;
    background: #123965;
}

.statistics {
    width: 250px;
    height: 54px;
    display: inline-block;
    vertical-align: middle;
    font-size: 18px;
    font-weight: bold;
    color: #FFFFFF;
    background: linear-gradient(90deg, RGBA(10, 43, 87, 0.1), RGBA(7, 77, 129, 1), RGBA(10, 43, 87, 0.1))
}

.statistics>img {
    width: 54px;
}

.optionList {
    height: 60px;
    width: 230px;
    margin-left: 24px;
    border-bottom: 1px solid RGBA(255, 255, 255, 0.1);
    font-size: 16px;
    font-weight: 400;
    color: #B1D0F4;
    display: inline-block;
    vertical-align: middle;
    line-height: 60px;
    padding-left: 30px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    position: relative;
}

.optionList>img {
    margin-left: 40px;
    width: 26px;
    position: absolute;
    right: 1px;
    top: 16px;
}

.ChickOut {
    padding-left: 20px;
    color: #1890ff;
}

.Btn {
    position: absolute;
    left: 78%;
    top: 16px;
    z-index: 999;
    font-size: 18px;
    text-align: center;
    color: #fff;
    font-weight: bold;
    line-height: 54px;
    width: 120px;
    height: 54px;
    background-image: url('/images/btn_bg.png');
    background-repeat: no-repeat;
    background-size: 100% 100%;
    margin-top: -7px;
    margin-right: 10px;
}

.Btn:hover {
    color: #fff;
    background-image: url('/images/btn_bg_select.png');
}

.times {
    position: absolute;
    left: 72%;
    top: 18px;
    float: left;
    line-height: 36px;
    font-size: 24px;
    font-weight: bold;
    color: #fff;
    margin-right: 10px;
}
</style>